package com.mengchengnet.chaperonage.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.util.ViewUtil;
import com.mengchengnet.chaperonage.view.CustomizedProgressDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/15.
 */

public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout lin_fankui,lin_upDate,lin_invite,lin_change;
    private Button exit;
    private RequestQueue requestQueue;
    private TextView tv_versionName,tv_now,tv_change;
    private CustomizedProgressDialog progressDialog;
    private String downLoad;
    private String userType;//判断当前用户是普通用户还是陪护人员
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initView();
    }

    private void initView() {
        userType=PreferenceUtil.getString(this,"userType");
        requestQueue= Volley.newRequestQueue(getApplication());
        toolbarState = TOOLBAR_STYLE_BACK_TITLE;
        initToolbar("设置");
        tv_now= (TextView) findViewById(R.id.setting_tv_now);
        tv_change= (TextView) findViewById(R.id.setting_tv_change);
        if (userType.equals("0")){
            tv_now.setText("用户版");
            tv_change.setText("切换到陪护版");
        }else {
            tv_now.setText("陪护版");
            tv_change.setText("切换到用户版");
        }
        exit= (Button) findViewById(R.id.setting_btn_exit);
        exit.setOnClickListener(this);
        lin_fankui= (LinearLayout) findViewById(R.id.setting_lin_fanKui);
        lin_fankui.setOnClickListener(this);
        lin_upDate= (LinearLayout) findViewById(R.id.setting_lin_up);
        lin_upDate.setOnClickListener(this);
        lin_change= (LinearLayout) findViewById(R.id.setting_lin_change);
        lin_change.setOnClickListener(this);
        lin_invite= (LinearLayout) findViewById(R.id.setting_lin_invite);
        lin_invite.setOnClickListener(this);
        tv_versionName= (TextView) findViewById(R.id.setting_tv_versionName);
        if(!PreferenceUtil.getString(this,"versionName").isEmpty()){
            tv_versionName.setText("当前版本"+PreferenceUtil.getString(this,"versionName"));
        }
        progressDialog=new CustomizedProgressDialog(this);
    }


    private void upDate() {
        StringRequest request = new StringRequest(Request.Method.POST, Url.GetUpdate,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("设置", "检查更新接口返回值："+result);
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }

                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("updateFlag").equals("-1")){
                                Toast.makeText(SettingActivity.this, "已经是最新版本", Toast.LENGTH_SHORT).show();
                                ViewUtil.hideProgressDialog();
                            }
                            else if(jsonObject.getString("updateFlag").equals("0")){
                                ViewUtil.hideProgressDialog();
                                downLoad=jsonObject.getString("downloadUrl");
                                showDialog("文件大小:"+jsonObject.getString("fileSize"));
                            }else {
                                ViewUtil.downloadApk(getApplicationContext(),jsonObject.getString("downloadUrl"),progressDialog,getParent());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(SettingActivity.this, "网络异常，注册失败，请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", "1");
                map.put("versionName", PreferenceUtil.getString(getApplication(),"versionCode"));
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.setting_btn_exit:
                if (userType.equals("0")){
                    PreferenceUtil.putBoolean(getApplication(),"isLogin",false);
                    startActivityAndFinish(LoginActivity.class);
                }else{
                    PreferenceUtil.putBoolean(getApplication(),"isLogin",false);
                    startActivityAndFinish(NurseLoginActivity.class);
                }

                break;
            case R.id.setting_lin_fanKui:
                Intent intent1 =new Intent(this,FeedBackActivity.class);
                startActivity(intent1);
                break;
            //检查更新
            case R.id.setting_lin_up:
                ViewUtil.showProgressDialog("检查更新中...");
                upDate();
                break;
            //分享给好友
            case R.id.setting_lin_invite:
                Intent intent2 =new Intent(this,ShareActivity.class);
                startActivity(intent2);

                break;
            //切换
            case R.id.setting_lin_change:
                if (userType.equals("0")){
                    PreferenceUtil.putBoolean(getApplication(),"isLogin",false);
                    Intent intent3=new Intent(this,NurseLoginActivity.class);
                    intent3.putExtra("mark","1");
                    startActivity(intent3);
                    finish();
                }else {
                    PreferenceUtil.putBoolean(getApplication(),"isLogin",false);
                    Intent intent3=new Intent(this,LoginActivity.class);
                    intent3.putExtra("mark","1");
                    startActivity(intent3);
                    finish();
                }

                break;
        }


    }

    private void showDialog(String msg){
        final AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("发现新版本");
        builder.setMessage(msg);
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ViewUtil.downloadApk(getApplicationContext(),downLoad,progressDialog,getParent());
            }
        });
        builder.setNegativeButton("稍后更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.show();
    }
}
